package com.yikes.srb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yikes.srb.common.result.PageResult;
import com.yikes.srb.common.utils.object.BeanUtils;
import com.yikes.srb.constant.hfb.FormHelper;
import com.yikes.srb.constant.hfb.HfbConst;
import com.yikes.srb.constant.hfb.RequestHelper;
import com.yikes.srb.leadingModle.form.userAccount.UserAccountAddForm;
import com.yikes.srb.leadingModle.form.userAccount.UserAccountEditForm;
import com.yikes.srb.leadingModle.form.userAccount.UserAccountQuery;
import com.yikes.srb.leadingModle.vo.UserAccountVO;
import com.yikes.srb.mapper.UserInfoMapper;
import com.yikes.srb.pojo.bo.TransFlowBO;
import com.yikes.srb.pojo.entity.UserAccount;
import com.yikes.srb.mapper.UserAccountMapper;
import com.yikes.srb.pojo.entity.UserInfo;
import com.yikes.srb.pojo.enums.ServiceWorkCodeEnum;
import com.yikes.srb.pojo.enums.TransTypeEnum;
import com.yikes.srb.service.TransFlowService;
import com.yikes.srb.service.UserAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yikes.srb.service.UserBindService;
import com.yikes.srb.util.LendNoUtils;
import com.yikes.srb.web.utils.As;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户账户 服务实现类
 * </p>
 *
 * @author guanrong.yin
 * @since 2024-12-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    private final UserInfoMapper userInfoMapper;

    private final TransFlowService transFlowService;

    private final UserBindService userBindService;

    @Override
    public PageResult<UserAccountVO> listPage(UserAccountQuery query) {

        Page<UserAccount> page = lambdaQuery()
                .eq(ObjectUtil.isNotNull(query.getUserId()), UserAccount::getUserId, query.getUserId())
                .eq(ObjectUtil.isNotNull(query.getAmount()), UserAccount::getAmount, query.getAmount())
                .eq(ObjectUtil.isNotNull(query.getFreezeAmount()), UserAccount::getFreezeAmount, query.getFreezeAmount())
                .page(Page.of(query.getPageNum(), query.getPageSize()));

        List<UserAccountVO> bean = BeanUtils.toBean(page.getRecords(), UserAccountVO.class);
        return PageResult.build(page.getTotal(), page.getPages(), bean);

    }

    @Override
    public UserAccountVO infoId(Long id) {

        UserAccount account = getById(id);
        return BeanUtils.toBean(account, UserAccountVO.class);
    }

    @Override
    public void create(UserAccountAddForm form) {

        UserAccount bean = BeanUtils.toBean(form, UserAccount.class);
        save(bean);

    }

    @Override
    public void edit(UserAccountEditForm form) {

        UserAccount bean = BeanUtils.toBean(form, UserAccount.class);
        updateById(bean);
    }

    @Override
    public void del(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public String commitCharge(BigDecimal chargeAmt, Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);
        String bindCode = userInfo.getBindCode();
        //判断账户绑定状态
        As.isNotBlank(bindCode, ServiceWorkCodeEnum.USER_NO_BIND_ERROR);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentBillNo", LendNoUtils.getNo());
        paramMap.put("bindCode", bindCode);
        paramMap.put("chargeAmt", chargeAmt);
        paramMap.put("feeAmt", new BigDecimal("0"));
        //检查常量是否正确
        paramMap.put("notifyUrl", HfbConst.RECHARGE_NOTIFY_URL);
        paramMap.put("returnUrl", HfbConst.RECHARGE_RETURN_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMap);
        paramMap.put("sign", sign);

        //构建充值自动提交表单
        return FormHelper.buildForm(HfbConst.RECHARGE_URL, paramMap);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public String notify(Map<String, Object> paramMap) {

        log.info("充值成功：" + JSONObject.toJSONString(paramMap));

        //判断交易流水是否存在
        //商户充值订单号
        String agentBillNo = (String) paramMap.get("agentBillNo");
        boolean isSave = transFlowService.isSaveTransFlow(agentBillNo);
        if (isSave) {
            log.warn("幂等性返回");
            return agentBillNo;
        }

        //充值人绑定协议号
        String bindCode = (String) paramMap.get("bindCode");
        //充值金额
        String chargeAmt = (String) paramMap.get("chargeAmt");

        //优化
        baseMapper.updateAccount(bindCode, new BigDecimal(chargeAmt), new BigDecimal(0));

        // 增加交易流水
        // 商户充值订单号
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(chargeAmt),
                TransTypeEnum.RECHARGE,
                "充值");
        transFlowService.saveTransFlow(transFlowBO);

        return agentBillNo;
    }

    @Override
    public BigDecimal getAccount(Long userId) {

        UserAccount userAccount = lambdaQuery().eq(UserAccount::getUserId, userId).one();

        return userAccount.getAmount();
    }

    @Override
    public String commitWithdraw(BigDecimal fetchAmt, Long userId) {

        //账户可用余额充足：当前用户的余额 >= 当前用户的提现金额
        //获取当前用户的账户余额
        BigDecimal amount = this.getAccount(userId);
        As.isTure(amount.doubleValue() >= fetchAmt.doubleValue(), ServiceWorkCodeEnum.NOT_SUFFICIENT_FUNDS_ERROR);

        String bindCode = userBindService.getBindCodeByUserId(userId);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentBillNo", LendNoUtils.getWithdrawNo());
        paramMap.put("bindCode", bindCode);
        paramMap.put("fetchAmt", fetchAmt);
        paramMap.put("feeAmt", new BigDecimal(0));
        paramMap.put("notifyUrl", HfbConst.WITHDRAW_NOTIFY_URL);
        paramMap.put("returnUrl", HfbConst.WITHDRAW_RETURN_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMap);
        paramMap.put("sign", sign);

        //构建自动提交表单
        String formStr = FormHelper.buildForm(HfbConst.WITHDRAW_URL, paramMap);
        return formStr;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void notifyWithdraw(Map<String, Object> paramMap) {
        log.info("提现成功");
        String agentBillNo = (String) paramMap.get("agentBillNo");
        boolean result = transFlowService.isSaveTransFlow(agentBillNo);
        if (result) {
            log.warn("幂等性返回");
            return;
        }

        String bindCode = (String) paramMap.get("bindCode");
        String fetchAmt = (String) paramMap.get("fetchAmt");

        //根据用户账户修改账户金额
        baseMapper.updateAccount(bindCode, new BigDecimal("-" + fetchAmt), new BigDecimal(0));

        //增加交易流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(fetchAmt),
                TransTypeEnum.WITHDRAW,
                "提现");
        transFlowService.saveTransFlow(transFlowBO);
    }
}
